package cn.com.fssg.platform.base.handler.impl.gsl.zw;

import cn.com.fssg.platform.base.handler.InterfaceHandler;
import cn.com.fssg.platform.biz.BizUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.util.ListUtils;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.core.namedparam.NamedParameterJdbcTemplate;
import org.springframework.stereotype.Component;

import javax.crypto.Cipher;
import javax.crypto.spec.SecretKeySpec;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.FileOutputStream;
import java.io.OutputStream;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.stream.Collectors;

/**
 * @Description: 工商联执委导出接口
 */
@Component
public class GslJcZwExportExcelCtl implements InterfaceHandler {

    private NamedParameterJdbcTemplate jdbcTemplate = BizUtil.cur().tenantMainJdbcTemplate();
//    @Autowired
//    private NamedParameterJdbcTemplate jdbcTemplate;

    @Override
    public Object run(HttpServletRequest request, JSONObject jsonObject) throws Exception {
        return null;
    }

    @Override
    public void run(HttpServletRequest request, HttpServletResponse response, JSONObject jsonObject) throws Exception {
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        String fileName = URLEncoder.encode("工商联届次执委信息", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        List<Map<String, Object>> result = this.getMapData(jsonObject);
        List<List<Object>> sheetData = this.convert(result);
        EasyExcel.write(response.getOutputStream()).head(this.head()).sheet("工商联届次执委信息").doWrite(sheetData);
        response.flushBuffer();
    }

    private List<List<String>> head() {
        List<List<String>> list = ListUtils.newArrayList();
        List<String> head1 = ListUtils.newArrayList();
        head1.add("执委姓名");
        List<String> head2 = ListUtils.newArrayList();
        head2.add("工商联职务");
        List<String> head3 = ListUtils.newArrayList();
        head3.add("单位职位");
        List<String> head4 = ListUtils.newArrayList();
        head4.add("手机号码");
        List<String> head5 = ListUtils.newArrayList();
        head5.add("状态");
        List<String> head6 = ListUtils.newArrayList();
        head6.add("任职时间");
        list.add(head1);
        list.add(head2);
        list.add(head3);
        list.add(head4);
        list.add(head5);
        list.add(head6);
        return list;
    }

    private List<List<Object>> convert(List<Map<String, Object>> mapList) {
        if (mapList.isEmpty()) {
            return Collections.emptyList();
        } else {
            List<String> headers = new ArrayList<>(((Map)mapList.get(0)).keySet());
            return mapList.stream().map((map) -> {
                List<Object> row = new ArrayList();
                headers.forEach((header) -> {
                    row.add(map.getOrDefault(header, ""));
                });
                return row;
            }).collect(Collectors.toList());
        }
    }

    // 模拟数据方法
    private List<Map<String, Object>> getMapData(JSONObject jsonObject) throws Exception {
        String jcId = jsonObject.getString("jcId");
        String userId = jsonObject.getString("userId");
        String querySql = "select * from gsl_jc_zw_user where gsl_session = :jcId";
        Map<String, Object> params = new HashMap<>();
        params.put("jcId", jcId);
        if (StringUtils.isNotBlank(userId)) {
            querySql += " and id = :userId";
            params.put("userId", userId);
        }

        List<Map<String, Object>> databaseList = jdbcTemplate.queryForList(querySql, params);

        List<Map<String, Object>> list = new ArrayList<>();
        if(!databaseList.isEmpty()) {
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            for (Map<String, Object> item : databaseList) {
                Map<String, Object> map = new HashMap<>();
                //执委姓名需要解密
                String userName = (String) item.get("username");
                String phone = (String) item.get("phone");
                String name = decrypt(userName, "usertokon");
                String phoneNum = decrypt(phone, "ankon");
                String gslPost = (String) item.get("gsl_post");
                String jobState = item.get("job_state").toString();
                map.put("执委姓名", name);
                map.put("任职时间", sdf.format(item.get("rz_date")));
                map.put("工商联职务", StringUtils.isEmpty(gslPost) ? "" : selectGslPost(gslPost));
                map.put("单位职位", item.get("company"));
                map.put("手机号码", phoneNum);
                map.put("状态", "1".equals(jobState) ? "在职" : "离职");
                list.add(map);
            }
        }
        return list;
    }

    private String selectGslPost(String post) {
        String gslPost = "";
        switch (post) {
            case "0":
                gslPost = "主席";
                break;
            case "1":
                gslPost = "副主席";
                break;
            case "2":
                gslPost = "副会长";
                break;
            case "3":
                gslPost = "秘书长";
                break;
            case "4":
                gslPost = "常委";
                break;
            case "5":
                gslPost = "执委";
                break;
        }
        return gslPost;
    }

    public static final String ALGORITHM = "AES";

    // 密钥补全
    public static byte[] padKey(byte[] key, int length) {
        return Arrays.copyOf(key, length);
    }

    /**
     * HEX 字符串转字节数组
     */
    public static byte[] hexToBytes(String hex) {
        byte[] bytes = new byte[hex.length() / 2];
        for (int i = 0; i < bytes.length; i++) {
            bytes[i] = (byte) Integer.parseInt(hex.substring(i * 2, i * 2 + 2), 16);
        }
        return bytes;
    }

    /** 解密 */
    public static String decrypt(String input, String keys) throws Exception {
        // 1. HEX 字符串 → 字节数组
        if(StringUtils.isNotBlank(input)) {
            byte[] cipherBytes = hexToBytes(input);
            byte[] keyBytes = padKey(keys.getBytes(StandardCharsets.UTF_8), 16);
            SecretKeySpec key = new SecretKeySpec(keyBytes, ALGORITHM);
            Cipher cipher = Cipher.getInstance(ALGORITHM);
            cipher.init(Cipher.DECRYPT_MODE, key);
            byte[] decrypted = cipher.doFinal(cipherBytes);
            return new String(decrypted, StandardCharsets.UTF_8);
        }
        return input;
    }

}
